package com.xmy.study.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.study.entity.StudentAccount;
import com.xmy.study.respons.ProfileResult;
import com.xmy.study.service.IStudentAccountService;
import org.apache.shiro.authc.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class StudentRealm extends XmyStudyRealm{

    @Autowired
    IStudentAccountService iStudentAccountService;

    /**
     * 认证方法
     *  参数：传递的用户名密码
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登录的用户名密码（token）
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String( upToken.getPassword());

        //System.out.print("username:"+username);
        //System.out.print("password:"+password);

        //2.根据用户名查询数据库
        QueryWrapper<StudentAccount> queryWrapper =  new QueryWrapper<>();

        queryWrapper.eq("account",username);
        queryWrapper.eq("pwd",password);

        ProfileResult profileResult = new ProfileResult();

        StudentAccount studentAccount = iStudentAccountService.getOne(queryWrapper);
        //3.判断用户是否存在或者密码是否一致
        if(studentAccount != null) {
            BeanUtils.copyProperties(studentAccount,profileResult);

            profileResult.setStudentAccount(studentAccount);
            //4.如果一致返回安全数据
            //构造方法：安全数据，密码，realm域名
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profileResult,studentAccount.getPwd(),this.getName());
            return info;
        }
        //5.不一致，返回null（抛出异常）
        return null;
    }
}
